package fer

import (
	"context"
	"math/rand"
	"strconv"
	"time"

	"gitee.com/k3x/urlx"
	"gitee.com/k3x/urlx/codec/json"
)

func FromICBC(ctx context.Context) (result Rates, err error) {
	defer result.SetDuration(time.Now())
	result.From = "工商银行"
	n := rand.New(rand.NewSource(time.Now().UnixNano())).Float64()
	var out struct {
		Code    int64  `json:"code,omitempty"`
		Message string `json:"message,omitempty"`
		Data    []struct {
			Name            string `json:"currencyCHName,omitempty"` // 货币名称
			Currency        string `json:"currencyENName,omitempty"` // 货币代号
			BuyingRate      string `json:"foreignBuy,omitempty"`     // 汇买价
			CashBuyingRate  string `json:"cashBuy,omitempty"`        // 钞买价
			SellingRate     string `json:"foreignSell,omitempty"`    // 汇卖价
			CashSellingRate string `json:"cashSell,omitempty"`       // 钞卖价
			MiddleRate      string `json:"reference,omitempty"`      // 中间价
			PublishDate     string `json:"publishDate,omitempty"`    //
			PublishTime     string `json:"publishTime,omitempty"`    //
		} `json:"data,omitempty"`
	}

	err = urlx.MacEdge(ctx).
		HeaderWith(urlx.Referer("http://www.icbc.com.cn/"), urlx.Accept("*/*")).
		Url("http://papi.icbc.com.cn/icbc/iepa/oproxy/rest/nsexchanges/latest?t=" + strconv.FormatFloat(n, 'f', 16, 64)).
		Process(json.Decode(&out))

	if err != nil {
		return
	}

	if len(out.Data) > 0 {
		result.Data = make(map[string]Rate, len(out.Data))
		for i, item := range out.Data {
			if i == 0 {
				result.UpdateAt, _ = time.ParseInLocation("2006-01-02 15:04:05", item.PublishDate+" "+item.PublishTime, locCST)
			}
			label := GetLabel(item.Currency)
			if label == "" {
				label = item.Name
			}
			result.Data[item.Currency] = Rate{
				Name:            label,
				Currency:        item.Currency,
				BuyingRate:      parseFloat(item.BuyingRate),
				CashBuyingRate:  parseFloat(item.CashBuyingRate),
				SellingRate:     parseFloat(item.SellingRate),
				CashSellingRate: parseFloat(item.CashSellingRate),
				MiddleRate:      parseFloat(item.MiddleRate),
			}
		}
	}

	return
}

func parseFloat(s string) float64 {
	f, _ := strconv.ParseFloat(s, 0)
	return f
}
